//
//  BaseLayer.m
//  xGame
//
//  Created by Max on 11-8-13.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "BaseLayer.h"
#import <mach/mach_time.h>

#define RANDOM_SEED() srandom((unsigned)(mach_absolute_time() & 0xFFFFFFFF))

int g_lastScore;

@interface BaseLayer(Private)
- (void)initClouds;
- (void)initCloud;

- (void)adjustAdSize;
@end


@implementation BaseLayer
@synthesize awView;

- (id)init {
    //	NSLog(@"Main::init");
	
	if(![super init]) return nil;
	
	RANDOM_SEED();
    
    CCSpriteBatchNode *spriteManager = [CCSpriteBatchNode batchNodeWithFile:@"sprites.png" capacity:10];
    [self addChild:spriteManager z:-1 tag:kSpriteManager];
    
    CCSprite *background = [CCSprite spriteWithBatchNode:spriteManager rect:CGRectMake(0, 0, 320, 480)];
    [spriteManager addChild:background];
    background.position = CGPointMake(160, 240);
    
	[self initClouds];
	[self schedule:@selector(step:)];
	
	return self;
}

- (void)dealloc {
    //	NSLog(@"Main::dealloc");
	[super dealloc];
}

- (void)initClouds {
    //	NSLog(@"initClouds");
	
	currentCloudTag = kCloudsStartTag;
	while(currentCloudTag < kCloudsStartTag + kNumClouds) {
		[self initCloud];
		currentCloudTag++;
	}
	
	[self resetClouds];
}

- (void)initCloud {
	
	CGRect rect;
	switch(random()%3) {
		case 0: rect = CGRectMake(336,16,256,108); break;
		case 1: rect = CGRectMake(336,128,257,110); break;
		case 2: rect = CGRectMake(336,240,252,119); break;
	}	
	
    CCSpriteBatchNode *spriteManager =(CCSpriteBatchNode *)[self getChildByTag:kSpriteManager];
    CCSprite *cloud =[CCSprite spriteWithBatchNode:spriteManager rect:rect];
    [spriteManager addChild:cloud z:3 tag:currentCloudTag];
	
    //	cloud.opacity = 128;
}

- (void)resetClouds {
    //	NSLog(@"resetClouds");
	
	currentCloudTag = kCloudsStartTag;
	
	while(currentCloudTag < kCloudsStartTag + kNumClouds) {
		[self resetCloud];
            
        CCSpriteBatchNode *spriteManager = (CCSpriteBatchNode*)[self getChildByTag:kSpriteManager];
		CCSprite *cloud = (CCSprite*)[spriteManager getChildByTag:currentCloudTag];
        CGPoint pos = cloud.position;
        pos.y -= 480.0f;
        cloud.position = pos;
		
		currentCloudTag++;
	}
}

- (void)resetCloud {
	
    //	AtlasSpriteManager *spriteManager = (AtlasSpriteManager*)[self getChildByTag:kSpriteManager];
    //	AtlasSprite *cloud = (AtlasSprite*)[spriteManager getChildByTag:currentCloudTag];
    
	CCSpriteBatchNode *spriteManager = (CCSpriteBatchNode*)[self getChildByTag:kSpriteManager];
	CCSprite *cloud = (CCSprite*)[spriteManager getChildByTag:currentCloudTag];
    
	float distance = random()%20 + 5;
	
	float scale = 5.0f / distance;
	cloud.scaleX = scale;
	cloud.scaleY = scale;
	if(random()%2==1) cloud.scaleX = -cloud.scaleX;
	
	CGSize size = cloud.contentSize;
	float scaled_width = size.width * scale;
	float x = random()%(320+(int)scaled_width) - scaled_width/2;
	float y = random()%(480-(int)scaled_width) + scaled_width/2 + 480;
	
//    NSLog(@"cloud(x,y)=(%f,%f)",x,y);
	cloud.position = ccp(x,y);
}

- (void)step:(ccTime)dt {
    //	NSLog(@"Main::step");
	
    //	AtlasSpriteManager *spriteManager = (AtlasSpriteManager*)[self getChildByTag:kSpriteManager];
    CCSpriteBatchNode *spriteManager = (CCSpriteBatchNode*)[self getChildByTag:kSpriteManager];
	
    //    NSLog(@"cloud step");
	int t = kCloudsStartTag;
	for(t=t; t < kCloudsStartTag + kNumClouds; t++) {
        //		AtlasSprite *cloud = (AtlasSprite*)[spriteManager getChildByTag:t];
        CCSprite *cloud = (CCSprite*)[spriteManager getChildByTag:t];
		CGPoint pos = cloud.position;
		CGSize size = cloud.contentSize;
		pos.x += 0.1f * cloud.scaleY;
		if(pos.x > 320 + size.width/2) {
			pos.x = -size.width/2;
		}
        
        //NSLog(@"cloud(x,y)=(%f,%f)",pos.x,pos.y);
		cloud.position = pos;
	}
	
}

- (void) onEnter {
    viewController = [[UIViewController alloc] init];    //设置viewController，用于显示广告，如果这个设置错误，则广告不能正常显示，也不能打开窗口显示广告。
    viewController.view = [[CCDirector sharedDirector] openGLView];
    awView = [AdWhirlView requestAdWhirlViewWithDelegate:self];
    
//    CGAffineTransform cgCTM = CGAffineTransformMakeRotation(CC_DEGREES_TO_RADIANS(-270));
//    cgCTM = CGAffineTransformTranslate(cgCTM,0,0);
//    [awView setTransform:cgCTM];    //由于设备是横向，需要旋转一定角度。
    awView.hidden=YES;        //开始时隐藏，以免影响主界面上的鼠标响应
    awView.center=CGPointMake(0,0);
    [viewController.view addSubview:awView];
    [super onEnter];
}

#pragma mark AdWhirlDelegate

- (NSString *) adWhirlApplicationKey {
    return @"487f961a9ce34cccb289d3dcbd071885";    //返回你在adwhirl上的key
}

- (UIViewController *)viewControllerForPresentingModalView{
    return viewController;
}

- (BOOL)adWhirlTestMode {
    return NO;
}

- (void)adWhirlDidReceiveAd:(AdWhirlView *)adWhirlView {
    if (YES == awView.hidden) {
        awView.hidden=NO;
    }
    [self adjustAdSize];
}

- (void)adjustAdSize {
//    [UIView beginAnimations:@"AdResize" context:nil];
//    [UIView setAnimationDuration:0.7];
//    CGSize adSize = [awView actualAdSize];
//    CGRect newFrame = awView.frame;
//    newFrame.size.height = adSize.width; //由于旋转了90度，需要调换高度和宽度
//    newFrame.size.width = adSize.height;
//    newFrame.origin =CGPointMake(0, 0);//这个坐标是正立时的坐标，以左上角为（0，0）
//    awView.frame = newFrame;
    awView.frame = CGRectMake(0, 430, 320, 50);//kAdWhirlViewDefaultFrame;
    
//    [UIView commitAnimations];    
}

@end
